import { FC, useState, useRef, useEffect, ReactElement } from 'react'
import { connect, Dispatch, Loading, LoginStateType, history } from 'umi'
import { Button, Form, Input, message, Card } from 'antd'
import { setStorage } from '@/utils'
import type { FormInstance } from 'antd'
import ForgetPassword from './components/forgetPassword'

import styles from './index.less'
type IProps = {
  login: LoginStateType
  dispatch: Dispatch
  loginLoding: Boolean
}

// 索引签名，任意属性
interface FormValues {
  [name: string]: any
}
let timeCount = 60
const LoignPage: FC<IProps> = ({
  login,
  dispatch,
  loginLoding
}): ReactElement => {
  const formRef = useRef<FormInstance>(null)
  const [visible, setVisible] = useState<boolean>(false)
  const [type, setType] = useState<number>(1)
  // 判断是否发送验证码
  const [flag, setFlag] = useState<boolean>(false)
  const [count, setCount] = useState<number>(timeCount)
  const timeRef = useRef<number | null>(null)
  const onFinish = (values: FormValues) => {
    handleLogin(values)
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }

  // 切换登录类型
  const switchType = (type: number): void => {
    if (type === 1) {
      clearInterval(timeRef.current!)
      setCount(timeCount)
      setFlag(false)
    }
    setType(type)
  }

  const cutCount = () => {
    setCount((prev) => prev - 1)
  }

  // 获取当前角色菜单权限
  const getLayoutMenu = (roleCode: string) => {
    dispatch({
      type: 'layoutmodel/function_getMenuList',
      callback: (response) => {
        const menu = response.obj.find((item: any) => item.url)
        if (menu.name === '指标赋分') {
          menu.url = menu.url.replace('evaluation', 'assignment')
        }
        if (roleCode === '2') {
          history.push('/evaluation')
          return
        }
        history.push(menu.url)
      }
    })
  }

  // 获取手机验证码
  const getCheckCode = () => {
    formRef.current?.validateFields(['phone'])
    const { phone } = formRef.current?.getFieldsValue(['phone'])
    dispatch({
      type: 'login/function_getSmsCode',
      payload: {
        phone
      },
      callback: (response) => {
        if (response.code == 200) {
          setFlag(true)
          cutCount()
          timeRef.current = window.setInterval(cutCount, 1000)
          message.success('验证码获取成功')
        }
      }
    })
  }

  useEffect(() => {
    if (count === 0) {
      clearInterval(timeRef.current!)
      setCount(timeCount)
      setFlag(false)
    }
  }, [count])
  // 登录
  const handleLogin = (values: FormValues) => {
    if (type === 1) {
      dispatch({
        type: 'login/function_login',
        payload: {
          ...values
        },
        callback: (response) => {
          if (response.code === 200) {
            getLayoutMenu(response.obj.roleCode)
            setStorage('userName', response.obj.userName)
          }
        }
      })
    } else {
      // 短信登录
      dispatch({
        type: 'login/function_smsLogin',
        payload: {
          ...values
        },
        callback: (response) => {
          if (response.code === 200) {
            getLayoutMenu(response.obj.roleCode)
            setStorage('userName', response.obj.userName)
          }
        }
      })
    }
  }

  useEffect(() => {
    formRef.current?.resetFields()
  }, [type])
  return (
    <>
      <div className={styles['login-page']}>
        <div className={styles['logo-title']}>
          <img
            src={require('../../assets/images/login/logo_white.png')}
            className={styles.logo}
          />
          <span className={styles.title}>
            新都区中小学“五育”并举育人质量综合评价平台
          </span>
        </div>
        <img
          src={require('../../assets/images/login/decorate.png')}
          className={styles['main-bg']}
        ></img>
        <Card>
          <div className={styles['type-switch']}>
            <div>
              <div className={styles.account} onClick={() => switchType(1)}>
                <span className={type == 1 ? styles.active : ''}>账号登陆</span>
              </div>
            </div>
            <div>
              <div className={styles.message} onClick={() => switchType(2)}>
                <span className={type == 2 ? styles.active : ''}>短信登陆</span>
              </div>
            </div>
          </div>
          <Form
            name="basic"
            initialValues={{}}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
            ref={formRef}
          >
            {type == 1 ? (
              <>
                <Form.Item
                  name="accountName"
                  rules={[
                    {
                      required: true,
                      message: '请输入账号!'
                    }
                  ]}
                >
                  <Input placeholder="请输入用户名/手机号/邮箱" />
                </Form.Item>
                <Form.Item
                  name="accountPass"
                  rules={[
                    {
                      required: true,
                      message: '请输入密码'
                    }
                  ]}
                >
                  <Input.Password placeholder="请输入密码" />
                </Form.Item>
              </>
            ) : (
              <>
                <Form.Item
                  name="phone"
                  rules={[
                    {
                      required: true,
                      message: '请输入手机号!'
                    },
                    {
                      pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
                      message: '请输入正确格式的手机号码'
                    }
                  ]}
                >
                  <Input placeholder="请输入手机号" />
                </Form.Item>
                <Form.Item
                  name="smsCode"
                  rules={[
                    {
                      required: true,
                      message: '请输入验证码!'
                    }
                  ]}
                >
                  <Input
                    placeholder="请输入验证码"
                    addonAfter={
                      <Button
                        //判断如果点击了获取验证码，就让button按钮上显示 *秒后重发送 并且button设置为disabled
                        onClick={getCheckCode}
                        disabled={flag}
                      >
                        {!flag ? '获取验证码' : `${count}s后重新获取`}
                      </Button>
                    }
                  />
                </Form.Item>
              </>
            )}

            {/* <Form.Item>
              <p className={styles['tip-message']}>
                登录即表示您同意《<span>用户协议</span>》和《
                <span>隐私协议</span>》
              </p>
            </Form.Item> */}
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className={styles['login-btn']}
                block
              >
                登录
              </Button>
            </Form.Item>
            <Form.Item>
              <div className={styles['bottom-tool']}>
                <span
                  className={styles['forget-password']}
                  onClick={() => {
                    setVisible(true)
                  }}
                >
                  忘记密码
                </span>
              </div>
            </Form.Item>
          </Form>

          <ForgetPassword
            visible={visible}
            hide={() => {
              setVisible(false)
            }}
          />
        </Card>
      </div>
    </>
  )
}

const mapStateToProps = ({
  login,
  loading
}: {
  login: LoginStateType
  loading: Loading
}) => {
  return {
    login,
    loginLoding: loading.models.login
  }
}

export default connect(mapStateToProps)(LoignPage)
